package watcher

import (
	"app/config"
	"app/daos"
	"app/env"
	"context"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/sirupsen/logrus"
	clientv3 "go.etcd.io/etcd/client/v3"
	"log"
	"path/filepath"
	"time"
)

// 检测配置文件变化reload

func WatchConfigChange() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		logrus.Fatal(err)
	}

	defer watcher.Close()
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}

				if event.Has(fsnotify.Write) {
					time.Sleep(1)
					fileName := filepath.Base(event.Name)
					config.Reload(fileName)
				}
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}

				log.Println("error:", err)
			}
		}
	}()

	// Add a path.
	err = watcher.Add(env.BaseDir + "/config")
	if err != nil {
		logrus.Fatal(err)
	}

	<-make(chan struct{})
}

func WatchEtcdChange() {
	rch := daos.GetEtcd().Watch(context.Background(), "/grpc", clientv3.WithPrefix()) // <-chan WatchResponse
	for wResp := range rch {
		for _, ev := range wResp.Events {
			fmt.Printf("Type: %s Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
		}
	}
}
